<?php
require_once 'config.php';

session_start();

// 验证部门用户权限
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'department') {
    header("Location: index.html");
    exit();
}

$department = $_SESSION['department'];
$conn = getDBConnection();

// 处理状态更新
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $status = $_POST['status'];
    $note = isset($_POST['note']) ? trim($_POST['note']) : null;
    
    // 获取选中人员
    if (isset($_POST['selected_personnel'])) {
        foreach ($_POST['selected_personnel'] as $name) {
            // 获取当前状态
            $stmt = $conn->prepare("SELECT status FROM personnel WHERE name = ?");
            $stmt->bind_param("s", $name);
            $stmt->execute();
            $result = $stmt->get_result();
            $old_status = $result->fetch_assoc()['status'];
            
            // 更新状态
            $stmt = $conn->prepare("UPDATE personnel SET status = ?, note = ? WHERE name = ?");
            $stmt->bind_param("sss", $status, $note, $name);
            $stmt->execute();
            
            // 记录状态变更历史
            $stmt = $conn->prepare("INSERT INTO status_history (personnel_id, name, old_status, new_status, note) 
                                  VALUES ((SELECT id FROM personnel WHERE name = ?), ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $name, $name, $old_status, $status, $note);
            $stmt->execute();
        }
    }
}

// 获取部门人员按状态分类
$statuses = ['在位', '休假', '公差勤务', '病假', '事假', '内部借调', '不在位'];
$personnel_by_status = [];
$status_counts = [];

foreach ($statuses as $status) {
    $stmt = $conn->prepare("SELECT name FROM personnel WHERE department = ? AND status = ? ORDER BY name");
    $stmt->bind_param("ss", $department, $status);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $personnel_by_status[$status] = $result->fetch_all(MYSQLI_ASSOC);
    $status_counts[$status] = count($personnel_by_status[$status]);
}

// 获取总人数
$total = array_sum($status_counts);

$conn->close();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $department; ?>状态管理</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="status-container">
        <h1><?php echo $department; ?>状态管理</h1>
        
        <div class="stats-panel">
            <h2>状态统计</h2>
            <p>总人数: <?php echo $total; ?></p>
            <ul>
                <?php foreach ($statuses as $status): ?>
                <li><?php echo $status; ?>: <?php echo $status_counts[$status]; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        
        <form method="post">
            <div class="status-selection">
                <h2>更新状态</h2>
                <div class="form-group">
                    <label for="status">选择状态:</label>
                    <select id="status" name="status" required>
                        <?php foreach ($statuses as $status): ?>
                        <option value="<?php echo $status; ?>"><?php echo $status; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group" id="note-container" style="display:none;">
                    <label for="note">备注:</label>
                    <textarea id="note" name="note" rows="3"></textarea>
                </div>
            </div>
            
            <div class="personnel-by-status">
                <?php foreach ($statuses as $status): ?>
                <div class="status-group">
                    <h3><?php echo $status; ?> (<?php echo $status_counts[$status]; ?>)</h3>
                    <ul class="personnel-list">
                        <?php foreach ($personnel_by_status[$status] as $person): ?>
                        <li>
                            <input type="checkbox" name="selected_personnel[]" value="<?php echo $person['name']; ?>" id="person_<?php echo $person['name']; ?>">
                            <label for="person_<?php echo $person['name']; ?>"><?php echo $person['name']; ?></label>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endforeach; ?>
            </div>
            
            <button type="submit" name="update_status" class="btn">更新状态</button>
        </form>
        
        <div class="navigation">
            <a href="department.php" class="btn">人员管理</a>
            <a href="history.php" class="btn">历史记录</a>
            <a href="logout.php" class="logout-btn">退出登录</a>
        </div>
    </div>
    
    <script>
        document.getElementById('status').addEventListener('change', function() {
            const noteContainer = document.getElementById('note-container');
            if (this.value === '不在位') {
                noteContainer.style.display = 'block';
                document.getElementById('note').setAttribute('required', '');
            } else {
                noteContainer.style.display = 'none';
                document.getElementById('note').removeAttribute('required');
            }
        });
    </script>
</body>
</html>